giveme tmp BHAR_gap5, clear
generate year = substr(交易日期, 1 ,4)
generate month = substr(交易日期, 6, 2)
drop if month < "05"
sort 证券代码 year 交易日期
by 证券代码 year: keep if _n == 1
forvalues i = 365 (5) 720 {
    drop BHAR`i'
}
rename 证券代码 stkcd
destring year, replace
replace year = year - 1
tostring year, replace
generate accper = year + "-12-31"
keep stkcd accper 交易日期 BHAR*
order stkcd accper 交易日期
savemy tmp annual_bhar


insheet using ./data/fd_risk.csv, clear
sort accper fd_risk
generate group = ""
by accper: replace group = "low" if _n < 0.1 * _N
by accper: replace group = "med" if _n < 0.55 * _N & _n > 0.45 * _N
by accper: replace group = "high" if _n > 0.9 * _N 
giveme tmp annual_bhar, merge on(stkcd accper) keep(1 3)
drop if BHAR5 == .
drop if group == ""
sort accper group
forvalues gap = 5 (5) 360 {
    bysort accper group: egen mBHAR`gap' = mean(BHAR`gap')
}
keep accper group mBHAR*
duplicates drop
reshape long mBHAR, i(accper group) j(lag)
sort group accper lag
order group accper lag mBHAR
reshape wide mBHAR, i(accper lag) j(group) string
generate id = _n
/* twoway (line mBHARhigh id) (line mBHARlow id) (line mBHARmed  id), xline(360) graphregion(color(white)) scheme(s2mono) */

sort accper lag
foreach type in high low med{
    generate fmBHAR`type' = mBHAR`type'
    by accper: replace fmBHAR`type' = mBHAR`type' - mBHAR`type'[_n - 1] if _n > 1
    replace fmBHAR`type' = fmBHAR`type' + 1
    replace fmBHAR`type' = 1 if _n == 1
    replace fmBHAR`type' = fmBHAR`type'[_n-1] * fmBHAR`type' if _n > 1
}
rename fmBHARhigh high
rename fmBHARmed median
rename fmBHARlow low
twoway (line high id) (line median id) (line low id), graphregion(color(white)) scheme(s2mono)

